#include "httpmgr.h"

#include "usermgr.h"

#include <QNetworkReply>



HttpMgr::~HttpMgr() {
    qDebug("HttpMgr::~HttpMgr");
}

HttpMgr::HttpMgr() { }

void HttpMgr::PostHttpReq(QUrl &&url, QByteArray &&data, ReqId id, Modules mod)
{
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader, QByteArray::number(data.length()));
    request.setRawHeader("Authorization", UserMgr::GetInstance()->getToken().toUtf8());

    auto _this = shared_from_this();//用来生产一个this的共享指针std::shared_ptr<HttpMgr>

    QNetworkReply *reply = manager.post(request, data);
    connect(reply, &QNetworkReply::finished, [_this, reply, id, mod](){
        if (reply->error() != QNetworkReply::NoError){
            _this->HttpFinish(id, reply->readAll(), mod, ErrorCodes::ERR_NETWORK);
            reply->deleteLater();
            return;
        }

        _this->HttpFinish(id, reply->readAll(), mod, ErrorCodes::SUCCESS);
        reply->deleteLater();
    });
}

void HttpMgr::HttpFinish(ReqId id, QByteArray res, Modules mod, ErrorCodes err)
{
    switch(mod){
    case Modules::REGISTERMOD:
        emit sig_reg_mod_finish(res, id, err);
        break;
    case Modules::LOGINMOD:
        emit sig_login_mod_finish(res, id, err);
        break;
    case Modules::GLOBALMOD:
        emit sig_global_mod_finish(res, id, err);
        break;
    }
}
